<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2024/4/10
 * Time: 12:01
 */

namespace plugin\admin\app\logic\withdraw;



use app\common\lib\YunZhangHu2;
use plugin\admin\app\model\user\UserIncomeFlowModel;
use plugin\admin\app\exception\AdminException;
use plugin\admin\app\logic\BaseLogic;

use plugin\admin\app\model\user\UserModel;
use plugin\admin\app\model\withdraw\UserWithdrawModel;
use support\Db;
use support\Request;
use support\Response;

class WithdrawLogic extends BaseLogic
{
    protected static $instance;

    public function __construct()
    {
        $this->model = new UserWithdrawModel();
    }

    public static function getInstance()
    {
        //        if(is_object(self::$instance)){
//            return self::$instance;
//        }

        return new self();
    }

    public function select(Request $request): Response
    {
        $field = $request->input('field');
        if($field==false){
            $request->inputSet('field','created_at');
            $request->inputSet('order','desc');
        }

        return parent::select($request);
    }

    protected function formatNormal($items, $total): Response
    {
        $userMap = $this->getListMapById(UserModel::getInstance(),$items,'user_sn','user_sn');
        foreach($items as &$val){
            $val['nickname'] = isset($userMap[$val['user_sn']])?$userMap[$val['user_sn']]['nickname']:'';

        }

        $totalData = $this->getWithdrawTotal();
        return json(['code' => 0, 'msg' => 'ok', 'count' => $total, 'data' => $items,'total_data'=>$totalData]);
    }

    public function getWithdrawTotal()
    {
        $data = [];
        $where = [];
        $param = request()->all();
        if (!empty($param['user_sn'])) {
            $where[] = ['user_sn', '=', $param['user_sn']];
        }
        //统计累计结算
        $where1 = $where;
        $where1[] = ['status','in',[1,2]];
        $where1['type'] = 1;
        $data['total_settle_amount'] = UserIncomeFlowModel::getInstance()->getWhere($where1)->sum('amount');

        //剩余可提现金额
        $where2 = $where;
        $where2[] = ['status','in',[1,2]];
        $data['total_can_withdraw_amount'] = UserIncomeFlowModel::getInstance()->getWhere($where2)->sum('amount');

        if (!empty($param['withdrawsn'])) {
            $where[] = ['withdrawsn', '=', $param['withdrawsn']];
        }

        if (!empty($param['created_at']) && !empty($param['created_at'][0]) && !empty($param['created_at'][1])) {
            $where[]   = ['createtd_at', 'between', $param['created_at']];
        }

        //累计提现金额
        $where3 = $where;
        $where3['status'] = 3;
        $data['total_withdraw_amount'] = $this->model->getWhere($where3)->sum('amount');

        //累计实付金额
        $where3 = $where;
        $where3['status'] = 3;
        $data['total_readly_amount'] = $this->model->getWhere($where3)->sum('readly_amount');

        //累计提现数次
        $where3 = $where;
        $where3['status'] = 3;
        $data['total_withdraw_nums'] = $this->model->getWhere($where3)->count();

        //累计提现人数
        $where3 = $where;
        $where3['status'] = 3;
        $subQuery = (new UserWithdrawModel())->getWhere($where3)->groupBy('user_sn')->select([Db::raw('count(1) counts')]);
        $data['total_withdraw_peoples'] = (new UserWithdrawModel())->setTable(Db::raw("({$subQuery->toSql()}) a"))->mergeBindings($subQuery->getQuery())->count();

        return $data;
    }

    public function insert(Request $request): Response
    {
        return parent::insert($request);
    }

    public function update(Request $request): Response
    {
        return parent::update($request);
    }

    protected function doUpdate($id, $data)
    {
        $withdraw = $this->model->find($id);
        if($withdraw==false){
            throw new AdminException(4020,'数据不存在');
        }
        if(($data['status']==1 || $data['status']==2) && $withdraw['status']!=0){
            throw new AdminException(4020,'待审核才可以审核');
        }elseif($data['status']==3 && $withdraw['status']!=1){
            throw new AdminException(4020,'审核通过才可以打款');
        }
        $withdraw->status = $data['status'];

        try{
            Db::connection('plugin.admin.mysql')->beginTransaction();
            if($data['status']==3){
                if($withdraw['type']==1){
                    //todo 1 个人提现云账户转账
                    //云账户转账
                    $notifyUrl = trim(config('app.app_url'),'/').'/index/notify/transfernotify';
                    $param = [
                        'transfer_order_sn'=>(string)time().$withdraw['withdrawsn'],
                        'payee_name'=>(string)$withdraw['truename'],
                        'payee_idcard'=>(string)$withdraw['idcard'],
                        'payee_account'=>(string)$withdraw['account'],
                        'amount'=>(string)$withdraw['amount'],
                        'remark'=>'用户提现',
                        'notify_url'=>(string)$notifyUrl,
                    ];
                    try{
                        $result = YunZhangHu2::getInstance()->submitAlipayOrder($param);
                        if(!empty($result['order_id']) && $result['order_id']==$param['transfer_order_sn']){
                            $withdraw->status = 5;
                            $withdraw->givemoney_time = date('Y-m-d H:i:s');
                            $result = $withdraw->save();
                        }
                    }catch (\Exception $e){
                        throw new AdminException(4020,$e->getMessage());
                    }
                }elseif($withdraw['type']==2){
                    //企业是财务转账
                    $withdraw->givemoney_time = date('Y-m-d H:i:s');
                    $result = $withdraw->save();
                }
            }elseif($data['status']==2 || $data['status']==1){
                $data['manage_remark'] && $withdraw->manage_remark = $data['manage_remark'];
                $result = $withdraw->save();
                if($data['status']==2){
                    //驳回要回退提现金额
                    UserIncomeFlowModel::getInstance()->getWhere(['source_table'=>UserWithdrawModel::getInstance()->getTable(),'sourceid'=>$withdraw->id])->delete();
                }
            }
            Db::connection('plugin.admin.mysql')->commit();
        }catch (AdminException $e){
            Db::connection('plugin.admin.mysql')->rollBack();
            throw $e;
        }catch (\Exception $e){
            Db::connection('plugin.admin.mysql')->rollBack();
            throw $e;
        }catch (\Throwable $e){
            Db::connection('plugin.admin.mysql')->rollBack();
            throw $e;
        }
    }
}